package com.mouse.magent.web.config;

import com.mouse.magent.common.entity.common.Result;
import com.mouse.magent.common.exception.SystemErrorType;
import com.mouse.magent.common.util.JsonUtil;
import com.mouse.magent.common.util.StringUtil;
import com.mouse.magent.web.entity.common.JwtInfo;
import com.mouse.magent.web.util.JwtUtil;
import com.mouse.magent.web.util.UserContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

@Configuration
public class WebCheckInterceptor implements HandlerInterceptor {
    private List<String> patterns = Arrays.asList("/auth/login");
    @Value("${custom.auth.enabled:false}")
    private Boolean authEnabled;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!authEnabled) return true;
        String url = request.getRequestURI();
        if (isInclude(url)) return true;
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtil.isBlank(token)) {
            sendJsonMessage(response, new Result(SystemErrorType.AUTH_ERROR));
            return false;
        }
        JwtInfo jwtInfo = JwtUtil.validateToken(token);
        if (jwtInfo == null) {
            sendJsonMessage(response, new Result(SystemErrorType.AUTH_ERROR));
            return false;
        }
        UserContext.getInstance().setContext(jwtInfo);
        return true;
    }

    private boolean isInclude(String url) {
        for (String pattern : patterns) {
            if (Pattern.matches(pattern, url)) {
                return true;
            }
        }
        return false;
    }

    public static void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JsonUtil.toJson(obj));
        writer.close();
        response.flushBuffer();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserContext.getInstance().clear();
    }
}
